import 'dart:convert';
import 'dart:typed_data';

class BleDataUtils {
  BleDataUtils._();

  static transData(List<int> data) {
    // 默认塞进头部
    var commonHeader = [
      0xAA, //170
      0xBB, //187
    ];

    // 塞入校验和
    int sum = calculateChecksum16(data);
    List<int> _sumList = intToNBytesHex<List<int>>(sum, 2, isSplit: true);
    data.addAll(_sumList);

    // 处理长度，塞进指令头
    String longStr = intToNBytesHex<List<int>>(data.length, 1, isSplit: false);
    commonHeader.add(int.parse("0x$longStr"));

    return [
      ...commonHeader,
      ...data,
    ];
  }

  static int calculateChecksum16(List<int> bytes) {
    int sum = bytes.reduce((value, element) => value + element);
    int checksum = sum & 0xFFFF;
    return checksum;
    // return int.parse(
    //     "0x${checksum.toRadixString(16).padLeft(4, '0').toUpperCase()}"); // 返回16位校验和
  }

  static List<Uint8List> splitImageData(Uint8List imageData, int mtu) {
    List<Uint8List> packets = [];
    int offset = 64; // 第一个数据包需要切掉的请求头大小
    // 特殊处理第一个数据包
    if (imageData.length > offset) {
      packets.add(imageData.sublist(0, offset));
    }

    // 处理剩余的数据包
    for (int i = offset; i < imageData.length; i += mtu) {
      int end = (i + mtu < imageData.length) ? i + mtu : imageData.length;
      packets.add(imageData.sublist(i, end));
    }
    return packets;
  }

  // 整数拆分成n个字节的16进制字符串
  static intToNBytesHex<T>(int value, int nBytes, {bool isSplit = true}) {
    // Calculate the number of bits from the number of bytes (1 byte = 8 bits)
    int nBits = nBytes * 8;
    // Convert the integer to a hexadecimal string, ensuring it fits into the specified number of bytes
    // by padding with zeros if necessary
    String hexRepresentation = value.toRadixString(16).padLeft(nBytes * 2, '0');
    // If the result is longer than expected (because of a very large number), truncate to fit the desired byte size
    if (hexRepresentation.length > nBytes * 2) {
      hexRepresentation =
          hexRepresentation.substring(hexRepresentation.length - nBytes * 2);
    }
    if (isSplit) {
      List<int> pairs = [];
      for (int i = 0; i < hexRepresentation.length; i += 2) {
        if (i + 2 <= hexRepresentation.length) {
          pairs.add(int.parse("0x${hexRepresentation.substring(i, i + 2)}"));
        } else {
          // 如果字符串长度为奇数，则将最后一个字符作为一对
          pairs.add(int.parse("0x${hexRepresentation.substring(i)}"));
        }
      }
      return pairs;
    } else {
      return hexRepresentation;
    }
  }

  // 把list 转换成 16进制字符串
  static List<String> listIntToHex(List<int> list) {
    return list
        .map((int number) =>
            number.toRadixString(16).padLeft(2, '0').toUpperCase())
        .toList();
  }
}
